//
//  HomeVC.swift
//  WBSwift
//
//  Created by maker on 11/8/16.
//  Copyright © 2016 maker. All rights reserved.
//

import UIKit
import SDWebImage
import MJRefresh

class HomeVC: BaseVC {
    //MARK:==========懒加载属性==========
    //导航中间的按钮
    lazy var titleBtn : UIButton = HorizontalButton(imageName: "navigationbar_arrow_down",selectName:"navigationbar_arrow_up" ,title: "maker")
    //动画工具条
    lazy var  popAnimate : PopAnimatorTool = PopAnimatorTool {[weak self] (isShow) -> () in
        self?.titleBtn.isSelected = isShow
    }
    // 数据源
    lazy var dataSource :[StatusViewModel] = [StatusViewModel]()
    //提示标签
    lazy var tipLbl : UILabel = UILabel()
    //图片浏览器动画
    fileprivate lazy var browerAnimator : ImageBrowerAnimator = ImageBrowerAnimator()
    
    //MARK:==========声明周期==========
    override func viewDidLoad() {
        super.viewDidLoad()
        //1.访客视图动画
        vistorView.startRotationAnimation()
        if !isLogin {
            return
        }
        
        //2.设置导航条
        setNavigationBar()
        
        //3.设置刷新控件
        setupHeader()
        setupFooter()
        
        //4.初始化提示标签
        setupTipLbl()
        
        //5.注册通知
        registerNotification()
        
    }

}

//MARK:==========设置 UI==========
extension HomeVC {
    
    ///1.设置导航 UI
    fileprivate func setNavigationBar(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop")

        navigationItem.titleView = titleBtn
        titleBtn.addTarget(self, action: #selector(HomeVC.titleBtnClick(_:)), for: .touchUpInside)
    
    }
    
    ///2.刷新头部
    func setupHeader (){
        //1.创建头部
        let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(HomeVC.loadNewData))
        tableView.mj_header = header
        
        //2.设置 header 属性
        header?.setTitle("下拉刷新", for: .idle)
        header?.setTitle("松开刷新", for: .pulling)
        header?.setTitle("正在刷新", for: .refreshing)
        
        //3.设置表格的属性
        self.tableView.estimatedRowHeight = 200
        //self.tableView.rowHeight = UITableViewAutomaticDimension
        
        //4.刷新表格
        header?.beginRefreshing()
    }
    
    ///3.刷新尾部
    func setupFooter() {
        tableView.mj_footer = MJRefreshAutoFooter(refreshingTarget: self, refreshingAction: #selector(HomeVC.loadMoreData))
        
    }
    
    ///4.初始化提示标签
    func setupTipLbl() {
        navigationController?.navigationBar.insertSubview(tipLbl, at: 0)
        tipLbl.backgroundColor = UIColor.orange
        tipLbl.frame = CGRect(x: 0, y: 10, width: screenWidth, height: 32)
        tipLbl.textColor = UIColor.white
        tipLbl.textAlignment = .center
        tipLbl.font = UIFont.systemFont(ofSize: 14)
        tipLbl.isHidden = true
    }
    
    ///5.注册通知
    func registerNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(HomeVC.showBrower(_:)), name: NSNotification.Name(rawValue: ShowBrower), object: nil)
    }

}

//MARK:==========事件监听==========
extension HomeVC{
    //导航标题点击
    func titleBtnClick(_ sender : HorizontalButton) {
        sender.isSelected = !sender.isSelected
        
        //弹出控制器
        let popVC = PopVC()
        //设置 modal 的样式为 custom 这样导航和底部不会被移除
        popVC.modalPresentationStyle = .custom
        popVC.transitioningDelegate = popAnimate
        popAnimate.transFrame = CGRect(x: 100, y: 55, width: 180, height: 250)
        present(popVC, animated: true, completion: nil)
    }
    
    //通知展示图片
    func showBrower(_ notice : Notification) {
        guard let imageDic = notice.userInfo else {
            return
        }
        let indexPath = imageDic[browerIndex] as! IndexPath
        let urls = imageDic[browerImageUrls] as! [URL]
        let object = notice.object as! PicCollection
        browerAnimator.browerAnimatorDelegate = object
        browerAnimator.indexpath = indexPath
        
        let browerVC = ImageBrowerVC(index: indexPath, imageUrls: urls)
        browerVC.modalPresentationStyle = .custom
        browerVC.transitioningDelegate = browerAnimator
        browerAnimator.dismissDelegate = browerVC
        present(browerVC, animated: true, completion: nil)
    }
    
}

//MARK:==========网络请求==========
extension HomeVC{
    @objc fileprivate func loadNewData(){
       getHomeData(true)
    }
    @objc fileprivate func loadMoreData(){
        getHomeData(false)
    }
    //1.加载数据
    func getHomeData(_ isLoadNew:Bool) {
        var since_id = 0
        var max_id = 0
        
        if isLoadNew {
            since_id = dataSource.first?.status?.mid ?? 0
        }else{
            max_id = dataSource.last?.status?.mid ?? 0
            max_id = max_id == 0 ? 0 : (max_id - 1)
        }
        
        NetWorkTool.shareInstance.getHomeData(since_id, max_id: max_id) { (result, error) in
            //1.校验是否有错误
            if error != nil{
                print(error)
                return
            }
            guard let resultArr = result else {
                return
            }
            
            //2.从数组中取出字典放入数据源中
            var temptArr = [StatusViewModel]()
            for dict in resultArr{
                let status = statusModel(dict: dict)
                let viewModel = StatusViewModel(status: status)
                temptArr.append(viewModel)
            }
            
            //3.把请求来的数据添加数据源中
            if isLoadNew {
                self.dataSource = temptArr + self.dataSource
            }else{
                self.dataSource += temptArr
            }
            
            //4.下载最新下载来的图片
            self.cacheImages(isLoadNew, viewModels: temptArr)
            
            //5.下载完所有的图片之后刷新表格
        }
    }
    
    //1.1缓存图片
    func cacheImages(_ isLoadNew:Bool, viewModels : [StatusViewModel]){
        //1.创建一个组
        //2.开始一个异步任务前进入组
        //3.完成一个异步任务离开组
        let group = DispatchGroup()
        
        for model in viewModels {
            guard let urls = model.imaURLs else {
                continue
            }
            //取出模型中的地址数组
            for url in urls {
                group.enter()
                SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (_, _, _, _, _) in
                    group.leave()
                })
            }
            
        }
        //4.通过 GCD 通知监听一个组的所有的任务执行完成后在某个线程中执行任务
        group.notify(queue: DispatchQueue.main) { 
            self.tableView.reloadData()
            if isLoadNew{
                if viewModels.count == 0 {
                    mprint("没有数据")
                }
                self.tableView.mj_header.endRefreshing()
                //提示更新多少
                self.showTipLbl(viewModels.count)
            }else{
                if viewModels.count == 0 {
                    mprint("没有更多数据")
                    self.tableView.mj_footer.endRefreshingWithNoMoreData()
                    return
                }
               self.tableView.mj_footer.endRefreshing()
            }
            
 
        }
    }
    
    //2.提示多少新消息
    fileprivate func showTipLbl(_ count:Int) {
        tipLbl.isHidden = false
        tipLbl.text = count == 0 ? "没有新微博" : "更新了\(count)条微博"
        
        //动画
        UIView.animate(withDuration: 1, animations: {
            self.tipLbl.setY(44)
            }, completion: { (_) in
                
               UIView.animate(withDuration: 1, delay: 2, options: [], animations: {
                    self.tipLbl.setH(0.01)
                }, completion: { (_) in
                    self.tipLbl.isHidden = true
                    self.tipLbl.setH(32)
                    self.tipLbl.setY(10)
               })
        }) 
    }
    
    
}

//MARK:==========表格代理==========
extension HomeVC{
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCellID") as! HomeCell
        
        cell.model = dataSource[indexPath.row]

        return cell
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model = dataSource [indexPath.row]
        return model.rowHeight
    }
}



